package com.jgzx.log;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.jgzx.utils.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author jackesy
 * @className: WebLogFilter
 * @description: 请求日志过滤器
 * @create 2020/12/4 0004 20:50
 **/
@Slf4j
@Component
public class WebLogFilter extends OncePerRequestFilter implements Ordered {

    private int order = Ordered.LOWEST_PRECEDENCE - 8;

    @Override
    public int getOrder() {
        return order;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        long start_time = System.currentTimeMillis();
        ContentCachingRequestWrapper wrapperRequest = new ContentCachingRequestWrapper(request);
        ContentCachingResponseWrapper wrapperResponse = new ContentCachingResponseWrapper(response);

        Map headerParams = WebUtil.getHeaderParams(request);
        Map requestParams = WebUtil.getRequestParams(request);

        filterChain.doFilter(wrapperRequest, wrapperResponse);
        String requestBody = WebUtil.getRequestBody(wrapperRequest);
        String request_uri = request.getRequestURI();
        String method = request.getMethod();
        if (StrUtil.isNotEmpty(request_uri) && !request_uri.startsWith("/actuator")) {
            log.info("请求URL:{}, 请求method:{}", request_uri, method);
            log.info("请求头参数：headerParams:{}", JSON.toJSONString(headerParams));
            if (MapUtil.isNotEmpty(requestParams)) {
                log.info("请求信息：requestParams:{}", JSON.toJSONString(requestParams));
            } else {
                log.info("请求信息：requestBody:{}", requestBody);
            }
            String responseBody = WebUtil.getResponseBody(wrapperResponse);
            if("application/json".equalsIgnoreCase(wrapperResponse.getContentType())){
                log.info("响应信息：response body:{}", responseBody);
            }
            long end_time = System.currentTimeMillis();
            log.info("{},请求耗时:{} 毫秒", request_uri, end_time-start_time);
        }

        wrapperResponse.copyBodyToResponse();
    }

}
